<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');
	
class QuestionMultiplePerRow{
	
	function QuestionMultiplePerRow(){
	}
	
	function display($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){		
		$return_content_array = array();
		$return = "";
		$answer = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$entered = "";
		$row_class = $params->table_row2;
		$row_class_ok = "true";
		$columns = $this->getColumns($question_id);
		$answers = $this->getAnswers($question_id);
		$validation = "";
		
		$return .= '<table width="100%" class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';
			$validation = $this->createValidation($answers, $question_id, $question_details["0"]["title"], $columns);						
		}
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_description.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		
		$return .= 			'<table width="100%">';		
		$return .= 	  			'<tr class="'.$params->column_heading.'">';
		$return .= 	     			'<td width="40%">';
		$return .= 	         			'<input type="hidden" value="checkbox" name="question['.$question_id.'][type]">';
    	$return .= 	         			'<input type="hidden" value="matrix" name="question['.$question_id.'][orientation]">';
		$return .= 	     			'</td>';
		//create table header
		if(isset($columns) && count($columns)>0){
			foreach($columns as $key=>$value){
				$return .= 	 		'<td align="center" class="'.$params->column_heading.'">'.$value["value"].'</td>';
			}
		}		
		$return .= 	  			'</tr>';
		//create table content
		if(isset($answers) && count($answers)>0 && isset($columns) && count($columns)>0){
			$edit_values = $this->getValue($question_id, $session_id);
			$all_values = array();
			if(count($edit_values) > 0){
				foreach($edit_values as $key=>$data_value){
					$all_values[$data_value["q_id"]."_".$data_value["a_id"]."_".$data_value["ac_id"]] = $data_value["ac_id"];
				}
			}			
			foreach($answers as $key=>$value){				
				$count = 1;
				if($row_class_ok == "true"){
					$row_class = $params->table_row2;
					$row_class_ok = "false";
				}
				else{
					$row_class = $params->table_row1;
					$row_class_ok = "true";
				}
				$return .= 	    '<tr class="'.$row_class.'">';
					$return .= 	    '<td align="left"><span class="'.$params->row_heading.'">'.trim($value["value"]).'</span></td>';
					foreach($columns as $key_col=>$val_col){
						$checked = "";
						if(isset($all_values[$question_id."_".$value["id"]."_".$val_col["id"]])){
							if(isset($completed["view_response"]) && $completed["view_response"]=="true"){
								$checked = ' checked="checked" ';
							}
						}																
						$return .= 	'<td align="center">';
						$return .= 	    '<input type="checkbox" '.$checked.' class="'.$params->checkbox.'" value="'.$val_col["id"].'" id="q'.$question_id.'a'.$value["id"].$count++.'" name="question['.$question_id.'][answer]['.$value["id"].'][]">';
						$return .= 	'</td>';
					}
				$return .= 	    '</tr>';				    
			}
		}
		$return .= 			'</table>';		
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		$return .= '</table>';
				
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="'.$value.'">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionMultiplePerRow">';		
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		
		return $return_content_array;
	}
	
	function getColumns($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answer_columns');
		$query->where("question_id=".intval($question_id));
		$query->order("id asc");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function getAnswers($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answers');
		$query->where("question_id=".intval($question_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}	
	
	function getValue($question_id, $session_id){
        if (!$session_id) { return NULL; }    
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('*');
		$query->from('#__ijoomla_surveys_result');
		$query->where("q_id=".intval($question_id)." and session_id=".intval($session_id));		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}
	
	function createValidation($answers, $question_id, $title, $columns){
		$result = "";
		$if_array = array();	
		
		foreach($answers as $key=>$value){
			$count = 1;
			foreach($columns as $key2=>$value2){
				$result .= '	i'.$count.' = document.getElementById("q'.$question_id.'a'.$value["id"].$count.'").checked ;'."\n";
				$if_array[] = 'i'.$count.' == false';
				$count++;
			}
			$result .= '	if('.implode(" && ", $if_array).'){'."\n".
					   '		alert(AlertText +"'.addslashes(trim($title)).'");'."\n".
					   '		return false;'."\n".
					   '	}'."\n";
			$if_array = array();			
		}
		return $result;
	}
	function save($id, $type, $session_id){
		$db =& JFactory::getDBO();			
		$all_answers = JRequest::getVar("question");					
		$answers = $all_answers[$id]["answer"];								
		
		if($this->answerExist($id, $session_id)){
			$sql = "delete from  #__ijoomla_surveys_result where q_id=".$id." and session_id=".$session_id;
			$db->setQuery($sql);
			$db->query();
		}
		
		foreach($answers as $key1=>$value1){
			foreach($value1 as $key2=>$value2){
				$sql = "insert into #__ijoomla_surveys_result(`q_id`, `a_id`, `m_id`, `ac_id`, `session_id`, `value`) values (";					
				$sql .= $id.", ".$key1.", 0, ".$value2.", ".$session_id.", 0";
				$sql .= ")";
				$db->setQuery($sql);
				$db->query();	
			}												
		}
	}	
	
	function answerExist($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$question_id." and session_id=".$session_id;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
	
	function editResult($id, $survey_id, $params, $i, $title, $all_responses_count){
		$answers = $this->getAnswers($id);
		$columns = $this->getColumns($id);
		
		$return  = '<table width="100%" style="border:1px solid #CCCCCC; border-collapse:collapse;">';
		$return .= 		'<tr>';
		$return .= 			'<td class="'.$params->question.'" colspan="'.(count($columns)+2).'" style="padding-left:5px;">';
		$return .= 				'<b>'.$i.". ".$title.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= 		'<tr>';
		$return .= 			'<td>';
		$return .= 			'</td>';
		
		foreach($columns as $c_key=>$c_value){
			$return .= '<td align="center">';
			$return .= 		$c_value["value"];
			$return .= '</td>';
		}
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_TOTAL_RESPONSE");
		$return .= 			'</td>';	
		$return .= 		'</tr>';
		$k = 0;
		foreach($answers as $a_key=>$a_value){
			$class = $params->table_row1;
			if($k%2 != 0){
				$class = $params->table_row2;
			}
			$k++;
			$return .= '<tr class="'.$class.'">';
			$return .= 		'<td align="right">';
			$return .= 			$a_value["value"];
			$return .= 		'</td>';
			$for_total = 0;	
			foreach($columns as $c_key=>$c_value){
				$return .= '<td align="center">';
				$count 	 = $this->countTotal($a_value["id"], $c_value["id"]);
				if(intval($all_responses_count) != "0"){
					$return .= 		@number_format( (($count * 100) / $all_responses_count), 2, '.', '') . " % (".$count.")";
				}
				$return .= '</td>';
				$for_total += $count;
			}
			$return .= 		'<td align="center">';
			$return .= 			$for_total;		
			$return .= 		'</td>';				
			$return .= '</tr>';	
		}
		$return .= 		'<tr>';
		$return .= 			'<td colspan="'.(count($columns)+1).'" style="padding-left:5px;">';
		$return .= 				'<b>'.JTExt::_("COM_SURVEYS_TOTAL_RESPONDENTS").':</b>';
		$return .= 			'</td>';
		$return .= 			'<td class="'.$params->total_background.'" align="center">';
		$return .= 				'<b>'.$this->countPerQuestion($id).'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= '</table>';
		return $return;		
	}
	
	function countTotal($a_id, $ac_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where a_id=".$a_id." and ac_id=".$ac_id.$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countPerQuestion($id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$id." group by session_id".$and;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function getValueFromDatabase($question_id, $session_id, $ac_id, $a_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('ac.value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answer_columns ac');
		$query->where("sr.q_id=".intval($question_id)." and sr.session_id=".intval($session_id)." and sr.ac_id=ac.id and sr.ac_id=".$ac_id." and a_id=".$a_id);		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();				
		return $result;
	}
	
	function getForHeader($id, $title){
		$return_array = array();
		$answers = $this->getAnswers($id);
		foreach($answers as $key=>$value){
			$return_array[] = $title." : ".trim($value["value"]);
		}
		$return = implode(",", $return_array);		
		return $return;
	}
	
	function getForRow($q_id, $sess_id){
		$answers = $this->getAnswers($q_id);
		$columns = $this->getColumns($q_id);
		$result_array = array();
					
		foreach($answers as $key=>$value){
			$response = $this->getValueFromDatabase($q_id, $sess_id, $columns["0"]["id"], $value["id"]);			
			if($response == NULL || count($response) == 0){
				$result_array[] = "NO ANSWER";
			}
			else{
				$result_array[] = trim($response["0"]["value"]);
			}
		}
		return implode(",", $result_array);
	}
		
	function getQuestionResultForEmail($q_id, $session_id, $title){
		$answers = $this->getAnswers($q_id);
		$columns = $this->getColumns($q_id);
		$return = $title.":"."\n";
		
		foreach($answers as $a_key=>$a_value){
			foreach($columns as $c_key=>$c_value){
				$result = $this->getValueFromDatabase($q_id, $session_id, $c_value["id"], $a_value["id"]);
				if(isset($result["0"]["value"]) && trim($result["0"]["value"]) != ""){
					$return .= "\t".trim($a_value["value"])." - ".trim($c_value["value"]).": ".trim($result["0"]["value"]);
				}
				else{
					$return .= "\t".trim($a_value["value"])." - ".trim($c_value["value"]).": ";
				}
				$return .= "\n";								
			}	
		}
		return $return;
	}	
	
	function checkCompleted($logic, $compare, $answer, $skip_answer){
		$return = false;
		
		if($logic == "OR"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = true;
						return $return;
					}
				}
			}
			elseif($compare == "different"){
				foreach($skip_answer as $key=>$value){
					if(in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
		}
		elseif($logic == "AND"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(!in_array($value, $answer)){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
			elseif($compare == "different"){
				foreach($answer as $key=>$value){
					if(in_array($value, $skip_answer)){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
		}			
	}
};

?>
